from django.conf import settings
from django.db import models
from django.core.validators import MinValueValidator
from django.forms import ValidationError
from django_filters.rest_framework import DjangoFilterBackend
from django.utils.translation import gettext_lazy as _
from apps.chefs.models import DjChef
from rest_framework import viewsets, filters
from core.permissions import IsAdminUser
from decimal import Decimal

#from apps.menu.serializers import VdjDishCategorySerializer, VdjDishCreateUpdateSerializer, VdjDishSerializer

class DjDishCategory(models.Model):
    """
    厨师菜品分类模型
    """
    name = models.CharField(
        max_length=100,
        verbose_name='分类名称',
        unique=True,  # 添加唯一约束
        help_text='分类名称(中文)'
    )
    name_en = models.CharField(
        max_length=100,
        verbose_name='英文分类名',
        blank=True,
        help_text='分类名称(英文)'
    )
    image = models.ImageField(
        upload_to='dj_dish_categories/',
        verbose_name='分类图片',
        blank=True,  # 允许为空
        null=True,   # 数据库允许NULL
        help_text='分类展示图片'
    )
    description = models.TextField(
        blank=True,
        verbose_name='分类描述',
        help_text='分类的详细描述'
    )
    is_active = models.BooleanField(
        default=True,
        verbose_name='是否启用',
        help_text='控制分类是否显示'
    )
    sort_order = models.PositiveSmallIntegerField(
        default=0,
        verbose_name='排序权重',
        help_text='数字越大排序越靠前'
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间'
    )
    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name='更新时间'
    )
    
    class Meta:
        verbose_name = '厨师菜品分类'
        verbose_name_plural = '厨师菜品分类'
        ordering = ['sort_order', 'name']
        indexes = [
            models.Index(fields=['is_active']),
            models.Index(fields=['sort_order']),
        ]
    
    def __str__(self):
        return self.name
    
    def clean(self):
        """模型验证逻辑"""
        from django.core.exceptions import ValidationError
        
        # 名称不能只包含空格
        if not self.name.strip():
            raise ValidationError({'name': '分类名称不能为空'})
        
        # 英文名为空时默认使用中文名
        if not self.name_en:
            self.name_en = self.name
    
    @property
    def display_name(self):
        """根据当前语言返回显示名称"""
        from django.utils import translation
        return self.name_en if translation.get_language() == 'en' else self.name


class DjDish(models.Model):
    """
    厨师菜品模型 包含配餐服务和餐具提供选项
    """
    chef = models.ForeignKey(
        DjChef,
        on_delete=models.CASCADE,
        related_name='dj_dishes',
        verbose_name='关联厨师'
    )
    category = models.ForeignKey(
        DjDishCategory,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        verbose_name='菜品分类',
        limit_choices_to={'is_active': True}  # 只允许选择活跃分类
    )
    
    # 基本信息
    name = models.CharField(
        max_length=100,
        verbose_name='菜品名称'
    )
    description = models.TextField(
        verbose_name='菜品描述'
    )
    base_price = models.DecimalField(
        max_digits=8,
        decimal_places=2,
        validators=[MinValueValidator(0)],
        default=0,
        verbose_name='基础价格'
    )
    display_price = models.DecimalField(max_digits=8, decimal_places=2, editable=False)

    dish_images = models.ManyToManyField(
    'DjDishImage',
    related_name='dish_relations',
    blank=True  # 这允许表单验证时不填写该字段
    )
    cloud_image_id = models.CharField(
        max_length=255, 
        blank=True, 
        null=True,
        verbose_name='云文件ID'
    )
    
    # 服务选项
    PROVIDE_CHOICES = (
        (True, '提供'),
        (False, '不提供'),
    )
    provide_meal_service = models.BooleanField(
        choices=PROVIDE_CHOICES,
        default=False,
        verbose_name='是否提供陪餐服务'
    )
    provide_utensils = models.BooleanField(
        choices=PROVIDE_CHOICES,
        default=False,
        verbose_name='是否提供餐具'
    )
    
    # 菜品属性
    is_spicy = models.BooleanField(
        default=False,
        verbose_name='是否辛辣'
    )
    is_vegetarian = models.BooleanField(
        default=False,
        verbose_name='是否素食'
    )
    prep_time = models.PositiveSmallIntegerField(
        default=30,
        verbose_name='准备时间(分钟)'
    )
    
    # 状态管理
    is_available = models.BooleanField(
        default=True,
        verbose_name='是否上架'
    )
    is_featured = models.BooleanField(
        default=False,
        verbose_name='是否推荐'
    )
    
    sort_order = models.PositiveSmallIntegerField(
        default=0,
        verbose_name='排序权重'
    )
    
    # 元数据
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间'
    )
    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name='更新时间'
    )
    
    class Meta:
        verbose_name = '厨师菜品'
        verbose_name_plural = '厨师菜品'
        ordering = ['-is_featured', '-created_at']
    
    def __str__(self):

        return f"{self.name} - {self.chef.username}"
    
    @property
    def final_price(self):
        """最终价格（基础价格+平台抽成，待管理系统实现）"""
        return self.base_price  # 后续将由管理系统计算
    def save(self, *args, **kwargs):
        # 自动计算展示价格
        if not hasattr(self, 'platform_fee_rate'):
            self.platform_fee_rate = 0.15  # 默认15%
        self.display_price = self.base_price * (1 + Decimal(str(self.platform_fee_rate)))
        super().save(*args, **kwargs)
    def clean(self):
        """验证分类是否有效"""
        if self.category and not self.category.is_active:
            raise ValidationError('不能选择已禁用的分类')


class DjDishImage(models.Model):
    """
    菜品图片模型（多图支持）
    """
    dish = models.ForeignKey(
        DjDish,
        on_delete=models.CASCADE,
        related_name='original_images',
        verbose_name='关联菜品',
        null=True,
        blank=True
    )
    image = models.ImageField(
        upload_to='dj_dish_images/',
        verbose_name='菜品图片'
    )
    is_primary = models.BooleanField(
        default=False,
        verbose_name='是否主图'
    )
    sort_order = models.PositiveSmallIntegerField(
        default=0,
        verbose_name='排序权重'
    )
    is_approved = models.BooleanField(
        default=True,
        verbose_name='是否审核通过'
    )
    approved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        verbose_name='审核人'
    )
    approved_at = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name='审核时间'
    )
    created_at = models.DateTimeField(auto_now_add=True) 
    
    class Meta:
        verbose_name = '菜品图片'
        verbose_name_plural = '菜品图片'
        ordering = ['is_primary', 'sort_order']
    
    def __str__(self):
        return f"{self.dish.name} 的图片"


class DjDishOption(models.Model):
    """
    菜品选项模型（如辣度、份量等）
    """
    dish = models.ForeignKey(
        DjDish,
        on_delete=models.CASCADE,
        related_name='options',
        verbose_name='关联菜品'
    )
    name = models.CharField(
        max_length=50,
        verbose_name='选项名称'
    )
    is_required = models.BooleanField(
        default=True,
        verbose_name='是否必选'
    )
    
    class Meta:
        verbose_name = '菜品选项'
        verbose_name_plural = '菜品选项'
    
    def __str__(self):
        return f"{self.dish.name} - {self.name}"


class DjDishOptionChoice(models.Model):
    """
    菜品选项选择项
    """
    option = models.ForeignKey(
        DjDishOption,
        on_delete=models.CASCADE,
        related_name='choices',
        verbose_name='关联选项'
    )
    name = models.CharField(
        max_length=50,
        verbose_name='选项值'
    )
    price_adjustment = models.DecimalField(
        max_digits=6,
        decimal_places=2,
        default=0,
        verbose_name='价格调整'
    )
    
    class Meta:
        verbose_name = '菜品选项值'
        verbose_name_plural = '菜品选项值'
    
    def __str__(self):
        return f"{self.option.name}: {self.name} ({self.price_adjustment:+})"
    

#厨师端后台部分
